<template>
  <div class="errurl-box">
    <el-form class="query-form" :inline="true" v-model="queryForm">
      <el-row>
        <el-form-item label="模块">
          <el-select v-model="queryForm.domain" placeholder="请选择" size="small" @change="changeQueryDomain">
            <el-option 
            v-for="item in queryForm.domains.dataArr" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="时间">
          <el-date-picker class="date-picker"
          size="small"
          v-model="queryForm.dateSelect"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" :loading="false" @click="getErrUrlList">查询</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-table :data="errUrl.dataArr" style="width: 100%;" v-loading="errUrl.isLoading" @expand-change="expandChange">
      <el-table-column type="expand" class-name="expand-column">
        <template slot-scope="props">
          <el-col :span="8">
            <div :id="props.row.error.replace(/\./g,'')+'series'" style="width: 100%; height:450px;" v-loading="lineLoading"></div>
          </el-col>
          <el-col :span="16">
            <div :id="props.row.error.replace(/\./g,'')" style="width: 100%; height:450px;" v-loading="pieLoading"></div>
          </el-col>
          <!-- <el-form label-position="right" label-width="92px" inline class="table-form-expand">
            <el-form-item>
              <label>异常名称</label>
              <span>{{ props.row.error }}</span>
            </el-form-item>
          </el-form> -->
        </template> 
      </el-table-column>
      <el-table-column prop="error" label="异常名称" width=""></el-table-column>
      <el-table-column prop="cnt" label="次数" show-overflow-tooltip width="" min-width="20"></el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="errUrl.currPage"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="errUrl.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="errUrl.totalCount">
    </el-pagination>
    

    <el-dialog :visible.sync="urlDetail.visible" :center="true">
      <span slot="title">
        <el-button class="defined-close-btn" type="primary" @click="urlDetail.visible = false">返回</el-button>
        <span class="err-title">url详情</span>
      </span>
      <el-table :data="urlDetail.dataArr">
        <el-table-column property="name" label="url" min-width="320"></el-table-column>
        <el-table-column property="value" label="错误数" min-width="120"></el-table-column>
        <el-table-column label="详情"> 
          <template slot-scope="scope">
            <el-button type="primary"  size="small" @click="showErrDetail(scope.row)">详情</el-button>
            </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleDetailSizeChange"
        @current-change="handleDetailCurrentChange"
        :current-page="urlDetail.currPage"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="urlDetail.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="urlDetail.totalCount">
      </el-pagination>
    </el-dialog>
    
    <el-dialog :visible.sync="errDetail.visible" :fullscreen="true" :center="true" v-loading="errDetail.isLoading">
      <span slot="title">
        <el-button class="defined-close-btn" type="primary" @click="errDetail.visible = false">返回</el-button>
        <span class="err-title">错误详情</span>
      </span>
      <el-table :data="errDetail.dataArr" style="width: 100%;">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="right" label-width="90px" inline class="table-form-expand">
              <el-form-item>
                <label>异常名称</label>
                <span>{{ props.row.error }}</span>
              </el-form-item>
              <el-form-item>
                <label>url</label>
                <span>{{ props.row.url }}</span>
              </el-form-item>
              <el-form-item>
                <label>异常摘要</label>
                <span>{{ props.row.exception }}</span>
              </el-form-item>
              <el-form-item>
                <label>发生时间</label>
                <span>{{ formatTime(props.row.date) }}</span>
              </el-form-item>
              <el-form-item class="width-block">
                <label>请求参数</label>
                <!-- <span>{{ props.row.requestMessage }}</span> -->
                <span v-html="props.row.requestMessage"></span>
              </el-form-item>
              <el-form-item class="width-block">
                <label>异常详情</label>
                <!-- <span>{{ props.row.stackTrace }}</span> -->
                <span v-html="props.row.stackTrace"></span>
              </el-form-item>
              <el-form-item class="width-block">
                <label>CAT详情</label>
                <!-- <span>{{ props.row.stackTrace }}</span> -->
                <a :href="props.row.catLink" target="_Blank">{{ props.row.catLink }}</a>
              </el-form-item>
            </el-form>
          </template> 
        </el-table-column>
        <el-table-column prop="error" label="异常名称"></el-table-column>
        <el-table-column prop="url" label="url" width=""></el-table-column>
        <el-table-column prop="exception" label="异常摘要" width="800"></el-table-column>
        <el-table-column prop="date" label="发生时间" width="170" :formatter="formatTime"></el-table-column>
        <el-table-column label="CAT详情"> 
          <template slot-scope="scope">
            <a :href="scope.row.catLink" target="_Blank">CAT详情</a>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleErrDetailSizeChange"
        @current-change="handleErrDetailCurrentChange"
        :current-page="errDetail.currPage"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="errDetail.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="errDetail.totalCount">
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
  import moment from 'moment'
  import echarts from 'echarts'
  import lodash from 'lodash'

  export default {
    data () {
      return {
        queryForm: {
          domain: 'api-gateway-app',
          domains: {
            dataArr: [
              {label: 'api-gateway-app', value: 'api-gateway-app'},
              {label: 'api-gateway-mpos', value: 'api-gateway-mpos'},
              {label: 'api-gateway-esb', value: 'api-gateway-esb'}
            ]
          },
          dateSelect: [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
        },
        errUrl: {
          isLoading: false,
          dataArr: [],
          currPage: 1,
          pageSize: 10,
          totalCount: 0
        },
        lineLoading: false,
        pieLoading: false,
        chartsInstance: {
          charts: {},
          chartsData: {}
        },
        urlDetail: {
          data: [],
          visible: false,
          title: '',
          dataArr: [],
          currPage: 1,
          pageSize: 10,
          totalCount: 0
        },
        errDetail: {
          isLoading: false,
          visible: false,
          dataArr: [],
          error: '',
          url: '',
          currPage: 1,
          pageSize: 10,
          totalCount: 0
        }
      }
    },
    activated () {
      this.getErrUrlList()
    },
    methods: {
      getErrUrlList () {
        var vm = this

        vm.errUrl.isLoading = true
        var params = {domain: this.queryForm.domain, currPage: this.errUrl.currPage, pageSize: this.errUrl.pageSize}

        if (vm.queryForm.dateSelect !== '' && vm.queryForm.dateSelect !== null) {
          params['startDate'] = vm.queryForm.dateSelect[0]
          params['endDate'] = vm.queryForm.dateSelect[1]
        }

        vm.$http({
          url: vm.$http.adornUrl('/errUrl/list'),
          methods: 'get',
          params: params
        }).then(({data}) => {
          if (data && data.code === 0) {
            vm.errUrl.dataArr = data.data.list
            vm.errUrl.totalCount = data.data.totalCount
            vm.errUrl.isLoading = false
          }
        })
      },
      getUrlDetailList () {
        var vm = this
        var currPage = this.urlDetail.currPage
        var pageSize = this.urlDetail.pageSize
        var offset = (currPage - 1) * pageSize
        vm.urlDetail.dataArr = vm.urlDetail.data.slice(offset, offset + pageSize)
        vm.urlDetail.totalCount = vm.urlDetail.data.length
        vm.urlDetail.visible = true
      },
      showErrDetail (row) {
        var vm = this
        vm.errDetail.currPage = 1
        vm.errDetail.error = row.error
        vm.errDetail.url = row.url
        vm.getErrDetailList()
      },
      getErrDetailList () {
        var vm = this

        vm.errDetail.isLoading = true

        var params = {domain: this.queryForm.domain, error: this.errDetail.error, url: this.errDetail.url, currPage: this.errDetail.currPage, pageSize: this.errDetail.pageSize}
        if (vm.queryForm.dateSelect !== '' && vm.queryForm.dateSelect !== null) {
          params['startDate'] = vm.queryForm.dateSelect[0]
          params['endDate'] = vm.queryForm.dateSelect[1]
        }

        vm.$http({
          url: vm.$http.adornUrl('/errUrl/urlDetail'),
          methods: 'get',
          params: params
        }).then(({data}) => {
          if (data && data.code === 0) {
            vm.errDetail.dataArr = data.data.list
            vm.errDetail.totalCount = data.data.totalCount
            vm.errDetail.isLoading = false
            vm.errDetail.visible = true
          }
        })
      },
      changeQueryDomain (value) {
        // this.getErrUrlList()
      },
      expandChange (row, expandedRows) {
        row.expand = !row.expand
        setTimeout(this.getErrDetail(row), 10)
      },
      getErrDetail (row) {
        // console.log(row)
        if (row.expand) {
          var vm = this
          vm.lineLoading = true
          vm.pieLoading = true
          var id = row.error.replace(/\./g, '')
          var params = {domain: this.queryForm.domain, error: row.error}
          if (vm.queryForm.dateSelect !== '' && vm.queryForm.dateSelect !== null) {
            params['startDate'] = vm.queryForm.dateSelect[0]
            params['endDate'] = vm.queryForm.dateSelect[1]
          }
          vm.$http({
            url: vm.$http.adornUrl('/errUrl/errDetail'),
            methods: 'get',
            params: params
          }).then(({data}) => {
            if (data && data.code === 0) {
              vm.chartsInstance.chartsData[id] = data.data
              vm.chartsInstance.chartsData[id].piece.map(function (item) {
                item.name = item.url
                item.value = item.cnt
              })
              // console.log(vm.chartsInstance.chartsData[id])
              var echartDiv = document.querySelector('#' + id)
              var echartSeriesDiv = document.querySelector('#' + id + 'series')
              if (echartDiv && echartSeriesDiv) {
                vm.chartsInstance.charts[id] = echarts.init(echartDiv)
                vm.chartsInstance.charts[id + 'series'] = echarts.init(echartSeriesDiv)
                this.initChartData(id)
                window.addEventListener('resize', () => {
                  vm.chartsInstance.charts[id].resize()
                  vm.chartsInstance.charts[id + 'series'].resize()
                })
              }
            }
          })
        }
      },
      initChartData (chartId) {
        var vm = this
        let isShow = vm.chartsInstance.chartsData[chartId].piece.length === 0
        var option = {
          title: [{
            text: 'URL分布',
            top: 'center',
            left: '65.5%',
            textStyle: {
              fontSize: 12,
              color: '#333'
            }
          }, {
            show: isShow,
            text: '暂无数据',
            top: '45%',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          }],
          tooltip: {
            formatter: function (params) {
              return params.name + ': ' + params.percent + '%'
            }
          },
          animationDurationUpdate: 1500,
          animationEasingUpdate: 'quinticInOut',
          roam: false, // 鼠标缩放及平移
          focusNodeAdjacency: false, // 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点
          // color: ['#345BA0', '#3F8B65', '#61B34A', '#6FA1CC', '#34A0D9', '#3191D8', '#378AAC', '#2B76B3'],
          // color: ['#2F4554', '#61A0A8', '#D48265', '#91C7AE', '#749F83', '#CA8622', '#BDA29A', '#6E7074', '#546570', '#C4CCD3'],
          color: ['#345BA0', '#00A65A', '#3F8B65', '#61B34A', '#605ca8', '#34A0D9', '#00C0EF', '#39CCCC', '#3191D8', '#378AAC', '#F39C12', '#FF851B'],
          series: [
            {
              name: 'url',
              type: 'pie',
              startAngle: 90,
              hoverAnimation: false,
              radius: [45, 72],
              center: ['70%', '50%'],
              itemStyle: {
                normal: {
                  borderWidth: 1,
                  borderColor: '#fff',
                  labelLine: {
                    length: 35,
                    show: false
                  }
                }
              },
              label: {
                normal: {
                  show: false,
                  formatter: '{d}%\n{b}'
                }
              },
              data: vm.chartsInstance.chartsData[chartId].piece
            },
            {
              name: 'url',
              type: 'pie',
              startAngle: 90,
              hoverAnimation: false,
              radius: [73, 78],
              center: ['70%', '50%'],
              itemStyle: {
                normal: {
                  borderWidth: 4,
                  borderColor: '#fff',
                  label: {
                    show: true,
                    formatter: '{b|{b}} {per|{d}}%',
                    rich: {
                      per: {
                        fontSize: 12,
                        fontWeight: 700
                      },
                      b: {
                        color: '#fff',
                        backgroundColor: '#334455',
                        padding: [1, 2],
                        borderRadius: 1
                      }
                    }
                  },
                  labelLine: {
                    show: true
                    //  length: 20
                  }
                }
              },
              data: vm.chartsInstance.chartsData[chartId].piece
            }
          ]
        }
        vm.chartsInstance.charts[chartId].setOption(option)
        vm.pieLoading = false
        vm.chartsInstance.charts[chartId].on('click', function (param) {
          vm.urlDetail.data = vm.chartsInstance.chartsData[chartId].piece
          vm.urlDetail.currPage = 1
          vm.getUrlDetailList()
        })

        let isSeriesShow = function () {
          if (vm.chartsInstance.chartsData[chartId].series && vm.chartsInstance.chartsData[chartId].series.length > 0) {
            return false
          } else {
            return true
          }
        }
        var seriesOption = {
          title: {
            show: isSeriesShow(),
            text: '暂无数据',
            top: '45%',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            show: false,
            top: 0,
            data: ['异常数'],
            itemGap: 10
          },
          // color: ['#3B73C3'],
          color: ['#4793C0'],
          dataZoom: [{
            type: 'inside',
            start: 0,
            end: 100
          }],
          xAxis: {
            boundaryGap: false,
            data: lodash.map(vm.chartsInstance.chartsData[chartId].series, 'dt')
          },
          yAxis: {
            name: '异常数（个）',
            axisTick: {
              interval: 0
            },
            splitLine: {
              show: false
            }
          },
          grid: [{
            top: '15%',
            left: 50,
            right: 30,
            bottom: '15%'
          }],
          series: [{
            name: '异常数',
            type: 'line',
            showSymbol: false,
            data: lodash.map(vm.chartsInstance.chartsData[chartId].series, 'value'),
            /* lineStyle: {
              color: '#3B73C3'
            }, */
            markLine: {
              data: [{
                type: 'average',
                name: '平均值'
              }],
              label: {
                // show: false
              }
              /* lineStyle: {
                color: '#3B73C3'
              } */
            }
          }]
        }
        vm.chartsInstance.charts[chartId + 'series'].setOption(seriesOption)
        vm.lineLoading = false
      },
      handleSizeChange (val) {
        this.errUrl.pageSize = val
        this.getErrUrlList()
      },
      handleCurrentChange (val) {
        this.errUrl.currPage = val
        this.getErrUrlList()
      },
      handleDetailSizeChange (val) {
        this.urlDetail.pageSize = val
        this.getUrlDetailList()
      },
      handleDetailCurrentChange (val) {
        this.urlDetail.currPage = val
        this.getUrlDetailList()
      },
      handleErrDetailSizeChange (val) {
        this.errDetail.pageSize = val
        this.getErrDetailList()
      },
      handleErrDetailCurrentChange (val) {
        this.errDetail.currPage = val
        this.getErrDetailList()
      },
      formatTime (row, column, cellValue, index) {
        if (cellValue !== null) {
          return moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return cellValue
        }
      }
    }
  }
</script>
<style scoped>
  .errurl-box .query-form{
    text-align: right;
    margin-bottom: 10px;
  }
  .errurl-box .el-button{
    padding: 8px 15px;
    font-size: 14px;
  }
  .errurl-box .expand-column{
    padding: 5px 10px;
  }
  .table-form-expand{
    font-size: 0;
  }
  .table-form-expand label {
    display: inline-block;
    width: 90px;
    color: #99a9bf;
    text-align: right;
    font-size: 14px;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
  .table-form-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .table-form-expand .el-form-item.width-block {
    display: block;
    width: 100%;
  }
  .defined-close-btn{
    position: absolute;
    left: 15px;
    top: 17px;
  }
  .err-title{
    font-size: 16px;
    margin-left: 10px;
  }
</style>

